package org.dizena.common.logger.appender;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.filter.LevelFilter;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
import ch.qos.logback.core.spi.FilterReply;
import ch.qos.logback.core.spi.ScanException;
import ch.qos.logback.core.util.FileSize;
import ch.qos.logback.core.util.OptionHelper;
import org.dizena.common.logger.LogbackProperties;

import java.nio.charset.StandardCharsets;

public class LogRollingFileAppender {
    private LoggerContext loggerContext;

    private LogbackProperties properties;

    public LogRollingFileAppender(LoggerContext loggerContext, LogbackProperties properties) {
        this.loggerContext = loggerContext;
        this.properties = properties;
    }

    public RollingFileAppender getRollingFileAppender(String path, Level level) throws ScanException {
        RollingFileAppender appender = new RollingFileAppender();

        // filter
        LevelFilter filter = new LevelFilter();
        filter.setLevel(level);
        filter.setOnMatch(FilterReply.ACCEPT);
        filter.setOnMismatch(FilterReply.DENY);
        filter.start();
        appender.addFilter(filter);
        appender.setContext(loggerContext);
        appender.setName(level.levelStr);
        appender.setFile(OptionHelper.substVars(path + "/" + level.levelStr.toLowerCase() + "/" + level.levelStr.toLowerCase() + ".log", loggerContext));
        appender.setAppend(true);
        appender.setPrudent(false);

        //RollingPolicy
        SizeAndTimeBasedRollingPolicy policy = new SizeAndTimeBasedRollingPolicy();
        policy.setContext(loggerContext);
        String fp = OptionHelper.substVars(path + "/" + level.levelStr.toLowerCase() + "/" + level.levelStr.toLowerCase() + ".%d{yyyy-MM-dd}.%i.log", loggerContext);
        policy.setFileNamePattern(fp);
        policy.setMaxHistory(properties.getMaxHistory());
        policy.setMaxFileSize(FileSize.valueOf(properties.getMaxFileSize()));
        policy.setTotalSizeCap(FileSize.valueOf(properties.getTotalSizeCap()));
        policy.setParent(appender);
        policy.start();
        appender.setRollingPolicy(policy);

        //encoder
        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(loggerContext);
        encoder.setPattern(properties.getPattern());
        encoder.setCharset(StandardCharsets.UTF_8);
        encoder.start();
        appender.setEncoder(encoder);
        appender.start();
        return appender;
    }


}
